<template>
  <div class="refund-report">
    <!-- 搜索筛选区域 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-search"></i> 查询条件
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="handleSearch" class="row g-3">
          <div class="col-md-3">
            <label for="dateRange" class="form-label">日期范围</label>
            <select 
              class="form-select" 
              id="dateRange" 
              v-model="searchForm.dateRange"
              @change="handleDateRangeChange"
            >
              <option value="">全部</option>
              <option value="7">最近7天</option>
              <option value="15">最近15天</option>
              <option value="30">最近30天</option>
              <option value="60">最近60天</option>
              <option value="custom">自定义</option>
            </select>
          </div>
          <div class="col-md-3" v-if="searchForm.dateRange === 'custom'">
            <label for="startDate" class="form-label">开始日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="startDate" 
              v-model="searchForm.startDate"
            >
          </div>
          <div class="col-md-3" v-if="searchForm.dateRange === 'custom'">
            <label for="endDate" class="form-label">结束日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="endDate" 
              v-model="searchForm.endDate"
            >
          </div>
          <div class="col-md-3">
            <label for="auditResult" class="form-label">审核状态</label>
            <select 
              class="form-select" 
              id="auditResult" 
              v-model="searchForm.auditResult"
            >
              <option value="">全部状态</option>
              <option value="0">待审核</option>
              <option value="1">审核通过</option>
              <option value="2">审核失败</option>
            </select>
          </div>
          <div class="col-md-3">
            <label for="settleStatus" class="form-label">结算状态</label>
            <select 
              class="form-select" 
              id="settleStatus" 
              v-model="searchForm.settleStatus"
            >
              <option value="">全部</option>
              <option value="0">未结算</option>
              <option value="1">已结算</option>
            </select>
          </div>
          <div class="col-md-3">
            <label for="bankCardHolder" class="form-label">银行卡持有人</label>
            <input 
              type="text" 
              class="form-control" 
              id="bankCardHolder" 
              v-model="searchForm.bankCardHolder"
              placeholder="请输入银行卡持有人姓名"
            >
          </div>
          <div class="col-md-3">
            <label for="auditUserName" class="form-label">审核人</label>
            <input 
              type="text" 
              class="form-control" 
              id="auditUserName" 
              v-model="searchForm.auditUserName"
              placeholder="请输入审核人"
            >
          </div>
          <div class="col-12">
            <button type="submit" class="btn btn-primary me-2" :disabled="loading">
              <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-search me-2"></i>
              查询
            </button>
            <button type="button" class="btn btn-outline-secondary" @click="resetSearch">
              <i class="bi bi-arrow-clockwise me-2"></i>
              重置
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 数据表格区域 -->
    <div class="card">
      <div class="card-header d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center gap-2">
        <h5 class="card-title mb-0">
          <i class="bi bi-table"></i> 退费报表生成
        </h5>
        <div class="d-flex flex-wrap align-items-center gap-2">
          <span class="text-muted me-3">共 {{ totalCount }} 条记录</span>
          <span class="text-info me-3" v-if="selectedItems.length > 0">
            已选择 {{ selectedItems.length }} 条
          </span>
          <button 
            class="btn btn-success btn-sm me-2" 
            @click="handleBatchSettle"
            :disabled="selectedItems.length === 0 || settling"
            v-if="canSettle"
          >
            <span v-if="settling" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="bi bi-calculator me-2"></i>
            退费结算 ({{ selectedItems.length }})
          </button>
          <button class="btn btn-outline-primary btn-sm me-2" @click="handleRefresh">
            <i class="bi bi-arrow-clockwise"></i> 刷新
          </button>
          <button 
            class="btn btn-sm" 
            :class="autoRefreshEnabled ? 'btn-success' : 'btn-outline-secondary'"
            @click="toggleAutoRefresh"
            title="启用/禁用自动刷新（30秒间隔）"
          >
            <i class="bi" :class="autoRefreshEnabled ? 'bi-clock-history' : 'bi-clock'"></i>
            {{ autoRefreshEnabled ? '自动刷新已开启' : '自动刷新已关闭' }}
          </button>
        </div>
      </div>
      <div class="card-body">
        <!-- 汇总信息 -->
        <div class="row mb-3" v-if="refundData.length > 0">
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center">
                <h6 class="card-title">总记录数</h6>
                <h4 class="text-primary">{{ totalCount }}</h4>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center">
                <h6 class="card-title">总退费金额(当页)</h6>
                <h4 class="text-success">¥{{ totalAmount.toFixed(2) }}</h4>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center">
                <h6 class="card-title">已选择记录</h6>
                <h4 class="text-info">{{ selectedItems.length }}</h4>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card bg-light">
              <div class="card-body text-center">
                <h6 class="card-title">已选择金额</h6>
                <h4 class="text-warning">¥{{ selectedAmount.toFixed(2) }}</h4>
              </div>
            </div>
          </div>
        </div>

        <!-- 数据表格 -->
        <div class="table-responsive" v-if="refundData.length > 0">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th style="width: 50px;">
                  <div class="form-check">
                    <input 
                      class="form-check-input" 
                      type="checkbox" 
                      :checked="isAllSelected"
                      @change="handleSelectAll"
                      :disabled="!canSettle"
                    >
                  </div>
                </th>
                <th>序号</th>
                <th>申请时间</th>
                <th>就诊人姓名</th>
                <th>就诊人卡号</th>
                <th>退费金额</th>
                <th>审核状态</th>
                <th>审核时间</th>
                <th>审核人</th>
                <th>结算状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in refundData" :key="item.id" :class="{ 'table-success': item.acctId, 'opacity-75': item.acctId }">
                <td>
                  <div class="form-check">
                    <input 
                      class="form-check-input" 
                      type="checkbox" 
                      :value="item.id"
                      v-model="selectedItems"
                      :disabled="!canSelectItem(item)"
                    >
                  </div>
                </td>
                <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
                <td>{{ formatDateTime(item.inputDate) }}</td>
                <td>
                  {{ item.patName }}
                  <i v-if="item.acctId" class="bi bi-check-circle-fill text-success ms-1" title="已结算"></i>
                </td>
                <td>{{ item.patientId }}</td>
                <td class="text-end">
                  <span class="badge bg-success">¥{{ parseFloat(item.refundBalance || 0).toFixed(2) }}</span>
                </td>
                <td>
                  <span class="badge" :class="getAuditStatusClass(item.auditResult)">
                    {{ getAuditStatusText(item.auditResult) }}
                  </span>
                </td>
                <td>{{ formatDateTime(item.auditDate) }}</td>
                <td>{{ item.auditUserName || '-' }}</td>
                <td>
                  <span class="badge" :class="item.acctId ? 'bg-primary' : 'bg-secondary'">
                    {{ item.acctId ? '已结算' : '未结算' }}
                  </span>
                  <div v-if="item.acctId" class="small text-muted mt-1">
                    结算ID: {{ item.acctId }}
                  </div>
                </td>
                <td>
                  <button 
                    class="btn btn-outline-primary btn-sm" 
                    @click="viewDetail(item)"
                    title="查看详情"
                  >
                    <i class="bi bi-eye me-1"></i>
                    详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空数据提示 -->
        <div v-else-if="!loading" class="text-center py-5">
          <i class="bi bi-inbox display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无数据</p>
        </div>

        <!-- 加载中 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="text-muted mt-3">正在加载数据...</p>
        </div>

        <!-- 分页组件 -->
        <div v-if="totalCount > pageSize" class="d-flex justify-content-center mt-4">
          <nav aria-label="分页导航">
            <ul class="pagination">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(1)" 
                  :disabled="currentPage === 1"
                >
                  首页
                </button>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(currentPage - 1)" 
                  :disabled="currentPage === 1"
                >
                  上一页
                </button>
              </li>
              <li 
                class="page-item" 
                :class="{ active: page === currentPage }"
                v-for="page in visiblePages" 
                :key="page"
              >
                <button class="page-link" @click="handlePageChange(page)">
                  {{ page }}
                </button>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(currentPage + 1)" 
                  :disabled="currentPage === totalPages"
                >
                  下一页
                </button>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(totalPages)" 
                  :disabled="currentPage === totalPages"
                >
                  末页
                </button>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>

    <!-- 结算确认模态框 -->
    <div class="modal fade" id="settleModal" tabindex="-1" aria-labelledby="settleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="settleModalLabel">
              <i class="bi bi-calculator"></i> 确认退费结算
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="alert alert-info">
              <i class="bi bi-info-circle"></i>
              您即将对选中的 <strong>{{ selectedItems.length }}</strong> 条记录进行退费结算，
              总金额为 <strong>¥{{ selectedAmount.toFixed(2) }}</strong>。
            </div>
            
            <!-- 选中记录详情 -->
            <div class="mb-3">
              <h6 class="text-muted">选中记录详情：</h6>
              <div class="table-responsive" style="max-height: 200px; overflow-y: auto;">
                <table class="table table-sm table-bordered">
                  <thead class="table-light">
                    <tr>
                      <th>患者姓名</th>
                      <th>患者卡号</th>
                      <th>退费金额</th>
                      <th>状态</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="item in selectedItemsData" :key="item.id">
                      <td>{{ item.patName }}</td>
                      <td>{{ item.patientId }}</td>
                      <td class="text-end">¥{{ parseFloat(item.refundBalance || 0).toFixed(2) }}</td>
                      <td>
                        <span class="badge bg-success">可结算</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            
            <div class="alert alert-success">
              <i class="bi bi-check-circle"></i>
              <strong>结算说明：</strong>
              <ul class="mb-0 mt-2">
                <li>结算后将生成唯一的结算ID</li>
                <li>所有选中记录将标记为已结算状态</li>
                <li>结算信息将记录操作人和操作时间</li>
                <li>可通过结算ID查询相关记录</li>
              </ul>
            </div>
            
            <div class="alert alert-warning">
              <i class="bi bi-exclamation-triangle"></i>
              <strong>重要提醒：</strong>结算操作不可撤销，请确认所有信息无误后继续。
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-success" @click="confirmSettle" :disabled="settling">
              <span v-if="settling" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-check-circle me-2"></i>
              确认结算
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="detailModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="detailModalLabel">
              <i class="bi bi-file-text-fill me-2"></i>
              退款申请详情
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" v-if="selectedItem">
            <!-- 基本信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-person-fill text-primary me-2"></i>
                  就诊人信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>申请ID：</strong>{{ selectedItem?.id }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请日期：</strong>{{ formatDateTime(selectedItem?.inputDate) }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>就诊人姓名：</strong>{{ selectedItem?.patName }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>就诊人卡号：</strong>{{ selectedItem?.patientId }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>身份证号：</strong>{{ selectedItem?.idNumber || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>联系电话：</strong>{{ selectedItem?.phoneNumber || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请退款金额：</strong>
                    <span v-if="selectedItem?.refundBalance && selectedItem?.auditResult === '1'" class="text-success">
                      实际退款 ¥{{ parseFloat(selectedItem?.refundBalance || 0).toFixed(2) }}
                      <small class="text-muted">(申请 ¥{{ parseFloat(selectedItem?.refundAmount || 0).toFixed(2) }})</small>
                    </span>
                    <span v-else class="text-primary">
                      ¥{{ parseFloat(selectedItem?.refundAmount || 0).toFixed(2) }}
                    </span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请类型：</strong>
                    <span class="badge bg-info">{{ selectedItem?.refundTypeName || '本人退费' }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>退款流水号：</strong>
                    <span v-if="selectedItem?.refundBalanceSn">{{ selectedItem?.refundBalanceSn }}</span>
                    <span v-else class="text-muted">-</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 银行信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-bank text-success me-2"></i>
                  {{ selectedItem?.refundTypeName === '代办人退费' ? '代办人银行信息' : '退款银行信息' }}
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>开户银行：</strong>
                    <span>{{ selectedItem?.refundTypeName === '代办人退费' ? (selectedItem?.publicAgentRefundBankName || '-') : (selectedItem?.refundBankName || '-') }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>银行卡号：</strong>
                    <span>{{ selectedItem?.refundTypeName === '代办人退费' ? (selectedItem?.publicAgentRefundBankCardNo || '-') : (selectedItem?.refundBankCardNo || '-') }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>开户行名称：</strong>{{ selectedItem?.refundTypeName === '代办人退费' ? (selectedItem?.publicAgentRefundBankOpenName || '-') : (selectedItem?.refundBankOpenName || '-') }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>开户行城市：</strong>{{ selectedItem?.refundTypeName === '代办人退费' ? (selectedItem?.publicAgentRefundBankCity || '-') : (selectedItem?.refundBankCity || '-') }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 代办人信息 -->
            <div v-if="selectedItem?.refundTypeName === '代办人退费'" class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-people-fill text-info me-2"></i>
                  代办人信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>代办人姓名：</strong>{{ selectedItem?.publicAgentName || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>与患者关系：</strong>{{ selectedItem?.publicAgentRelation || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>代办人电话：</strong>{{ selectedItem?.publicAgentPhoneNumber || '-' }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 审核信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-clipboard-check-fill text-warning me-2"></i>
                  审核信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>审核状态：</strong>
                    <span class="badge" :class="getAuditStatusClass(selectedItem?.auditResult)">{{ getAuditStatusText(selectedItem?.auditResult) }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>审核人：</strong>{{ selectedItem?.auditUserName || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>审核时间：</strong>{{ formatDateTime(selectedItem?.auditDate) }}
                  </div>
                  <div class="col-12 mb-3" v-if="selectedItem?.auditComment">
                    <strong>审核备注：</strong>{{ selectedItem?.auditComment }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 结算信息 -->
            <div v-if="selectedItem?.acctId" class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-calculator-fill text-primary me-2"></i>
                  结算信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>结算ID：</strong>{{ selectedItem?.acctId }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>结算状态：</strong>
                    <span class="badge bg-primary">已结算</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import api from '@/utils/api'
import { Modal } from 'bootstrap'

// 响应式数据
const loading = ref(false)
const settling = ref(false)
const refundData = ref([])
const selectedItem = ref(null) // 选中的详情项
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const selectedItems = ref([])
const selectedItemsData = ref([]) // 存储所有选中项的详细数据
const autoRefreshTimer = ref(null) // 自动刷新定时器
const autoRefreshEnabled = ref(false) // 自动刷新开关，默认关闭

// 搜索表单
const searchForm = ref({
  dateRange: '30',
  startDate: '',
  endDate: '',
  auditResult: '1', // 默认审核通过
  settleStatus: '0', // 默认未结算
  bankCardHolder: '', // 新增银行卡持有人查询条件
  auditUserName: '' // 新增审核人查询条件
})

// 计算属性
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))

const visiblePages = computed(() => {
  const total = totalPages.value
  const current = currentPage.value
  const delta = 2
  const range = []
  const rangeWithDots = []
  
  for (let i = Math.max(2, current - delta); i <= Math.min(total - 1, current + delta); i++) {
    range.push(i)
  }
  
  if (current - delta > 2) {
    rangeWithDots.push(1, '...')
  } else {
    rangeWithDots.push(1)
  }
  
  rangeWithDots.push(...range)
  
  if (current + delta < total - 1) {
    rangeWithDots.push('...', total)
  } else {
    rangeWithDots.push(total)
  }
  
  return rangeWithDots.filter((item, index, arr) => arr.indexOf(item) === index && item !== 1 || index === 0)
})

const totalAmount = computed(() => {
  return refundData.value.reduce((sum, item) => sum + parseFloat(item.refundBalance || 0), 0)
})

const selectedAmount = computed(() => {
  return selectedItemsData.value.reduce((sum, item) => sum + parseFloat(item.refundBalance || 0), 0)
})

const isAllSelected = computed(() => {
  const selectableItems = refundData.value.filter(item => canSelectItem(item))
  return selectableItems.length > 0 && selectableItems.every(item => selectedItems.value.includes(item.id))
})

const canSettle = computed(() => {
  return searchForm.value.auditResult === '1' // 只有审核通过的记录才能结算
})

// 方法
const handleDateRangeChange = () => {
  if (searchForm.value.dateRange && searchForm.value.dateRange !== 'custom') {
    const days = parseInt(searchForm.value.dateRange)
    const today = new Date()
    // 确保使用本地时间而不是UTC时间
    const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate())
    const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days)
    
    // 格式化为YYYY-MM-DD格式
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    searchForm.value.endDate = formatDate(endDate)
    searchForm.value.startDate = formatDate(startDate)
  }
}

const handleSearch = async () => {
  currentPage.value = 1
  selectedItems.value = []
  selectedItemsData.value = []
  await loadRefundData()
}

const resetSearch = () => {
  searchForm.value = {
    dateRange: '30',
    startDate: '',
    endDate: '',
    auditResult: '1', // 默认审核通过
    settleStatus: '0', // 默认未结算
    bankCardHolder: '', // 新增银行卡持有人查询条件
    auditUserName: '' // 新增审核人查询条件
  }
  selectedItems.value = []
  selectedItemsData.value = []
  handleDateRangeChange()
  handleSearch()
}

const handleRefresh = () => {
  selectedItems.value = []
  selectedItemsData.value = []
  loadRefundData()
}

const handlePageChange = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadRefundData()
  }
}

const handleSelectAll = (event) => {
  const selectableItems = refundData.value.filter(item => canSelectItem(item))
  if (event.target.checked) {
    // 添加选中项
    const newSelectedIds = selectableItems.map(item => item.id)
    selectedItems.value = [...new Set([...selectedItems.value, ...newSelectedIds])]
    
    // 同步更新selectedItemsData
    const newSelectedData = selectableItems.filter(item => !selectedItemsData.value.some(existing => existing.id === item.id))
    selectedItemsData.value = [...selectedItemsData.value, ...newSelectedData]
  } else {
    // 移除选中项
    const selectableIds = selectableItems.map(item => item.id)
    selectedItems.value = selectedItems.value.filter(id => !selectableIds.includes(id))
    
    // 同步更新selectedItemsData
    selectedItemsData.value = selectedItemsData.value.filter(item => !selectableIds.includes(item.id))
  }
}

const canSelectItem = (item) => {
  return item.auditResult === '1' && !item.acctId // 只有审核通过且未结算的记录才能选择
}

const handleBatchSettle = async () => {
  if (selectedItems.value.length === 0) {
    showToast('请选择要结算的记录', 'warning')
    return
  }
  
  // 在结算前检查选中记录的状态
  try {
    showToast('正在检查记录状态...', 'info')
    
    // 重新加载当前页数据以检查状态
    await loadRefundData()
    
    // 检查选中的记录是否仍然可以结算
    const currentPageIds = refundData.value.map(item => item.id)
    const invalidIds = []
    
    for (const selectedId of selectedItems.value) {
      const currentItem = refundData.value.find(item => item.id === selectedId)
      if (currentItem && currentPageIds.includes(selectedId)) {
        // 检查当前页的记录状态
        if (!canSelectItem(currentItem)) {
          invalidIds.push(selectedId)
        }
      }
    }
    
    if (invalidIds.length > 0) {
      // 移除无效的选中项
      selectedItems.value = selectedItems.value.filter(id => !invalidIds.includes(id))
      selectedItemsData.value = selectedItemsData.value.filter(item => !invalidIds.includes(item.id))
      
      showToast(`检测到 ${invalidIds.length} 条记录状态已变更，已自动移除。请重新确认选择`, 'warning')
      
      if (selectedItems.value.length === 0) {
        showToast('所有选中记录状态已变更，无法进行结算', 'warning')
        return
      }
    }
    
    const modal = new Modal(document.getElementById('settleModal'))
    modal.show()
  } catch (error) {
    console.error('检查记录状态失败:', error)
    showToast('检查记录状态失败，请重试', 'error')
  }
}

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    // 首先尝试从localStorage中获取用户信息对象
    // 尝试多个可能的键名
    const possibleKeys = ['userInfo', 'user', 'currentUser', 'loginUser']
    
    for (const key of possibleKeys) {
      const userInfoStr = localStorage.getItem(key)
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          if (userInfo && userInfo.fullName) {
            console.log(`从localStorage的${key}键获取到用户信息:`, userInfo)
            return {
              fullName: userInfo.fullName,
              username: userInfo.username || userInfo.id || 'admin'
            }
          }
        } catch (e) {
          console.warn(`解析localStorage中的${key}失败:`, e)
        }
      }
    }
    
    // 如果都没找到，输出localStorage中所有的键用于调试
    console.log('localStorage中的所有键:', Object.keys(localStorage))
    console.log('localStorage内容调试:', {
      userInfo: localStorage.getItem('userInfo'),
      user: localStorage.getItem('user'),
      currentUser: localStorage.getItem('currentUser'),
      loginUser: localStorage.getItem('loginUser')
    })
    
    // 如果没有找到userInfo或解析失败，尝试从token中获取
    const token = localStorage.getItem('token')
    if (!token) {
      console.warn('未找到token，使用默认用户信息')
      return {
        fullName: '系统用户',
        username: 'system'
      }
    }
    
    const tokenParts = token.split('.')
    if (tokenParts.length !== 3) {
      console.warn('token格式不正确，使用默认用户信息')
      return {
        fullName: '系统用户',
        username: 'system'
      }
    }
    
    const base64Payload = tokenParts[1]
    // 处理base64编码中的填充问题
    let paddedPayload = base64Payload
    while (paddedPayload.length % 4) {
      paddedPayload += '='
    }
    
    // 替换URL安全的base64字符
    paddedPayload = paddedPayload.replace(/-/g, '+').replace(/_/g, '/')
    
    const payload = JSON.parse(atob(paddedPayload))
    
    return {
      fullName: payload.full_name || payload.name || payload.unique_name || '系统用户',
      username: payload.name || payload.sub || payload.unique_name || 'system'
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    // 如果token解析失败，返回默认用户信息而不是抛出错误
    console.warn('使用默认用户信息')
    return {
      fullName: '系统用户',
      username: 'system'
    }
  }
}

const confirmSettle = async () => {
  if (selectedItems.value.length === 0) return
  
  settling.value = true
  
  try {
    // 获取当前用户信息
    const currentUser = getCurrentUser()
    console.log('当前用户信息:', currentUser)
    
    const response = await api.post('/api/refund/batch-settle', {
      refundIds: selectedItems.value,
      operatorName: currentUser.username,
      operatorFullName: currentUser.fullName
    })
    
    if (response.data && response.data.success) {
      const result = response.data.data
      showToast(`批量结算成功！结算ID：${result.acctId}，共结算 ${result.settledCount} 条记录，总金额：¥${result.totalAmount}`, 'success')
      
      // 结算成功后，将数据插入到HIS数据库
      try {
        await insertSettledDataToHis(result.acctId)
      } catch (error) {
        console.error('插入HIS数据库失败:', error)
        showToast('结算成功，但插入HIS数据库失败，请联系管理员', 'warning')
      }
      
      selectedItems.value = []
      selectedItemsData.value = []
      await loadRefundData()
      
      // 关闭模态框
      const modal = Modal.getInstance(document.getElementById('settleModal'))
      modal.hide()
    }
  } catch (error) {
    console.error('结算失败:', error)
    const errorMessage = error.response?.data?.message || error.message
    
    // 检查是否为并发冲突错误
    if (errorMessage.includes('已被其他用户结算') || errorMessage.includes('并发') || errorMessage.includes('重复结算')) {
      showToast('结算失败：所选记录中部分已被其他用户结算，请刷新数据后重新选择', 'warning')
      // 自动刷新数据
      setTimeout(async () => {
        await loadRefundData()
        selectedItems.value = []
        selectedItemsData.value = []
      }, 1000)
    } else {
      showToast('批量结算失败：' + errorMessage, 'error')
      // 结算失败时重新刷新数据并取消所有选择
      setTimeout(async () => {
        await loadRefundData()
        selectedItems.value = []
        selectedItemsData.value = []
      }, 1000)
    }
  } finally {
    settling.value = false
  }
}

const loadRefundData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNumber: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 处理日期范围，确保结束日期包含当天的所有数据
    if (searchForm.value.startDate) {
      params.startDate = searchForm.value.startDate + 'T00:00:00'
    }
    if (searchForm.value.endDate) {
      params.endDate = searchForm.value.endDate + 'T23:59:59'
    }
    if (searchForm.value.auditResult) {
      params.auditResult = searchForm.value.auditResult
    }
    if (searchForm.value.settleStatus) {
      params.settleStatus = searchForm.value.settleStatus
    }
    if (searchForm.value.bankCardHolder) {
      params.bankCardHolder = searchForm.value.bankCardHolder
    }
    if (searchForm.value.auditUserName) {
      params.auditUserName = searchForm.value.auditUserName
    }
    
    const response = await api.get('/api/Refund/paged', { params })
    
    if (response.data) {
      refundData.value = response.data.items || []
      totalCount.value = response.data.totalCount || 0
      
      // 根据当前查询条件决定是否启动自动刷新
      startAutoRefresh()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    showToast('加载数据失败，请重试', 'error')
    refundData.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
  
  return Promise.resolve() // 确保返回Promise以支持链式调用
}

// 自动刷新功能
const startAutoRefresh = () => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value)
  }
  
  if (autoRefreshEnabled.value && searchForm.value.auditResult === '1' && searchForm.value.settleStatus === '0') {
    // 只在查看未结算的审核通过记录时启用自动刷新
    autoRefreshTimer.value = setInterval(async () => {
      try {
        await loadRefundData()
      } catch (error) {
        console.warn('自动刷新失败:', error)
      }
    }, 30000) // 每30秒刷新一次
  }
}

// 查看详情
const viewDetail = (item) => {
  selectedItem.value = item
  const modal = new Modal(document.getElementById('detailModal'))
  modal.show()
}

// 获取审核状态样式类
const getAuditStatusClass = (auditResult) => {
  switch (auditResult) {
    case '0':
      return 'bg-warning'
    case '1':
      return 'bg-success'
    case '2':
      return 'bg-danger'
    default:
      return 'bg-secondary'
  }
}

// 获取审核状态文本
const getAuditStatusText = (auditResult) => {
  switch (auditResult) {
    case '0':
      return '待审核'
    case '1':
      return '审核通过'
    case '2':
      return '审核拒绝'
    default:
      return '未知状态'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 将结算数据插入到HIS数据库
const insertSettledDataToHis = async (acctId) => {
  try {
    // 获取当前登录用户信息
    const currentUser = getCurrentUser()
    console.log('当前登录用户信息:', currentUser)
    
    // 1. 根据acctId获取结算后的退费记录详情
    const refundsResponse = await api.get(`/api/refund/by-acct-id/${acctId}`)
    if (!refundsResponse.data || !refundsResponse.data.success) {
      throw new Error('获取结算记录失败')
    }
    
    const refunds = refundsResponse.data.data
    if (!refunds || refunds.length === 0) {
      console.warn('未找到结算记录')
      return
    }
    
    // 2. 获取结算记录信息（lzfy_refund_acct表数据）
    const acctResponse = await api.get(`/api/RefundAcct/by-acct-id/${acctId}`)
    if (!acctResponse.data) {
      throw new Error('获取结算信息失败')
    }
    
    const acctData = acctResponse.data
    
    // 3. 为每条退费记录创建HIS数据库记录
     const createPromises = refunds.map(async (refund) => {
       const prepayRefundDetailData = {
         balanceSn: refund.refundBalanceSn || '', // 退费流水号
         refundBalance: refund.refundBalance, // 实际退款金额
         patientId: refund.patientId, // 患者ID
         patName: refund.patName, // 患者姓名
         refundTypeName: refund.refundTypeName || '线上退费', // 退费类型名称
         auditDate: refund.auditDate, // 审核日期
         acctDate: acctData.inputDate, // 结算日期（使用结算记录的录入时间）
         auditUserId: currentUser.username, // 使用当前登录用户的username
         auditUserName: refund.auditUserName, // 审核人姓名
         bankCardHolder: refund.bankCardHolder, // 银行卡开户人
         acctId: acctId, // 结算ID
         refundBankCity: refund.refundBankCity, // 退费银行城市
         publicAgentRefundBankCity: refund.publicAgentRefundBankCity // 公共代理退费银行城市
       }
      
      // 调用PrepayRefundDetail/create接口
      return api.post('/api/PrepayRefundDetail/create', prepayRefundDetailData)
    })
    
    // 4. 批量执行插入操作
    const results = await Promise.allSettled(createPromises)
    
    // 5. 检查结果
    const successCount = results.filter(result => result.status === 'fulfilled').length
    const failCount = results.filter(result => result.status === 'rejected').length
    
    if (failCount > 0) {
      console.error('部分记录插入HIS数据库失败:', results.filter(r => r.status === 'rejected'))
      throw new Error(`${successCount}条记录插入成功，${failCount}条记录插入失败`)
    }
    
    console.log(`成功将${successCount}条结算记录插入HIS数据库`)
    
  } catch (error) {
    console.error('插入HIS数据库失败:', error)
    throw error
  }
}

const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value)
    autoRefreshTimer.value = null
  }
}

const toggleAutoRefresh = () => {
  autoRefreshEnabled.value = !autoRefreshEnabled.value
  if (autoRefreshEnabled.value) {
    startAutoRefresh()
    showToast('已启用自动刷新（30秒间隔）', 'info')
  } else {
    stopAutoRefresh()
    showToast('已关闭自动刷新', 'info')
  }
}

const showToast = (message, type = 'info') => {
  // 简单的提示实现，可以根据需要使用更复杂的Toast组件
  const alertClass = {
    'success': 'alert-success',
    'error': 'alert-danger',
    'warning': 'alert-warning',
    'info': 'alert-info'
  }[type] || 'alert-info'
  
  const toast = document.createElement('div')
  toast.className = `alert ${alertClass} alert-dismissible fade show position-fixed`
  toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;'
  toast.innerHTML = `
    ${message}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  `
  
  document.body.appendChild(toast)
  
  setTimeout(() => {
    if (toast.parentNode) {
      toast.parentNode.removeChild(toast)
    }
  }, 5000)
}

// 生命周期
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const today = new Date()
  // 确保使用本地时间而不是UTC时间
  const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)
  
  // 格式化为YYYY-MM-DD格式
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  searchForm.value.endDate = formatDate(endDate)
  searchForm.value.startDate = formatDate(startDate)
  
  loadRefundData()
  // 默认不启动自动刷新
})

// 组件销毁时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})

// 监听选中项变化，同步更新selectedItemsData
watch(selectedItems, (newSelectedIds, oldSelectedIds) => {
  // 找出新增的选中项
  const addedIds = newSelectedIds.filter(id => !oldSelectedIds.includes(id))
  const removedIds = oldSelectedIds.filter(id => !newSelectedIds.includes(id))
  
  // 添加新选中的项目数据
  if (addedIds.length > 0) {
    const addedItems = refundData.value.filter(item => addedIds.includes(item.id))
    const newItems = addedItems.filter(item => !selectedItemsData.value.some(existing => existing.id === item.id))
    selectedItemsData.value = [...selectedItemsData.value, ...newItems]
  }
  
  // 移除取消选中的项目数据
  if (removedIds.length > 0) {
    selectedItemsData.value = selectedItemsData.value.filter(item => !removedIds.includes(item.id))
  }
}, { deep: true })

// 监听搜索条件变化
watch(() => searchForm.value.auditResult, () => {
  selectedItems.value = [] // 切换审核状态时清空选择
  selectedItemsData.value = [] // 同时清空选中项数据
})
</script>

<style scoped>
.refund-report {
  padding: 0;
}

.table th {
  background-color: #495057;
  color: white;
  border-color: #495057;
}

.table-hover tbody tr:hover {
  background-color: rgba(0, 123, 255, 0.1);
}

.badge {
  font-size: 0.75em;
}

.form-check-input:disabled {
  opacity: 0.3;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  border: 1px solid rgba(0, 0, 0, 0.125);
}

.alert {
  border-radius: 0.375rem;
}

.pagination .page-link {
  color: #0d6efd;
}

.pagination .page-item.active .page-link {
  background-color: #0d6efd;
  border-color: #0d6efd;
}
</style>